package admin.controllers;

import helpers.PaginatorHelper;
import helpers.ValidateHelper;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import models.EmailModel;

import data.EmailData;

public class ListEmailServlet extends HttpServlet{
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		String s = (String) request.getParameter("s");
		int page = 1;
		boolean nextPage = false;
		boolean prevPage = false;
		
		ArrayList<EmailModel> emails = new ArrayList<EmailModel>();
		EmailData emailData = new EmailData();
		
		if (s != null && ValidateHelper.isEmail(s)) {
			EmailModel email = emailData.getEmail(s);
			if (email != null) {
				emails.add(email);
			}
		} else {
			try {
				page = Integer.parseInt((String) request.getParameter("page"));
			} catch (Exception e) {}
			
			
			emailData.setLimit(20);
			emailData.setPage(page);
			emails = emailData.list();
			
			
			if (emails.size() == emailData.getLimit()) {
				nextPage = true;
			}
			
			if (page > 1) {
				prevPage = true;
			}
		}
		
		
		
		//Get paginate
		String queryString = request.getQueryString();
		String requestURI = request.getRequestURI();
		PaginatorHelper paginator = new PaginatorHelper(queryString);
		paginator.setUrl(requestURI);
		
		request.setAttribute("s", s);
		request.setAttribute("paginator", paginator);
		request.setAttribute("prevPage", prevPage);
		request.setAttribute("nextPage", nextPage);
		request.setAttribute("emails", emails);
		request.setAttribute("page", page);
		
		try {
			request.getRequestDispatcher("/admin/pages/list_email.jsp").forward(request, response);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}
